package hasthi.actuators.actions;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import hasthi.actuators.CreateServiceAction;
import hasthi.actuators.ResourceBasedAction;
import hasthi.common.HasthiException;
import hasthi.common.HasthiException.FaultCode;
import hasthi.common.constants.HasthiConstants;
import hasthi.common.constants.WSDMConstants;
import hasthi.metamodel.resource.ManagedResource;
import hasthi.metamodel.resource.ManagedService;

public class RestartAction extends ResourceBasedAction{
    protected static Log log = LogFactory.getLog(HasthiConstants.LOGGER_NAME);
    private String name;
    private List<ManagedResource> hostAgents;
    
    public RestartAction(ManagedResource resource) {
        super(resource);
        name =  RestartAction.class.getName()+"|" + resource.getName();
    }
    @Override
    public void execute() throws HasthiException {
        try{
        ShutDownAction shutDownAction = new ShutDownAction(resource);
        shutDownAction.init(actionContext);
        shutDownAction.execute();
        }catch(Exception e){
            log.warn("Shutdown failed in restart,but create service will work",e);
        }
        
        CreateServiceAction createServiceAction = new CreateServiceAction(resource);
        createServiceAction.setHostAgents(hostAgents);
        String hostName = resource.getProperty(WSDMConstants.HOSTNAME_PARAM.getLocalPart());
        if(hostName != null){
            createServiceAction.setTargetHost(hostName);    
        }else{
            throw new HasthiException("Restart only supported for services, not for "+ resource,FaultCode.InvaliedRequest);
        }
        createServiceAction.init(actionContext);
        createServiceAction.execute();
    }
    @Override
    public String getActionID() {
        return name;
    }

    @Override
    public String toString() {
        return name;
    }
    public void setHostAgents(List<ManagedResource> hostAgents) {
        this.hostAgents = hostAgents;
    }
    
}
